package com.sgb.contract.view.ui.openaccount;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sgb.contract.R;
import com.sgb.contract.base.BaseActivity;
import com.sgb.contract.databinding.ContractActivityAccountEditBinding;
import com.sgb.contract.test.model.OpenAccountDetailEntity;
import com.sgb.contract.utils.ArouterConfigs;
import com.sgb.contract.utils.StringUtils;
import com.sgb.contract.view.ui.accountdetail.AccountDetailActivity;
import com.swgk.core.BR;
import com.swgk.core.dialog.RoundDialog;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * 描述：修改经办人
 *
 * @author qiangHeNooo
 * <p>
 * 时间：2021.11.02
 */
@Route(path = ArouterConfigs.AR_ACCOUNT_EDIT)
public class AccountEditActivity extends BaseActivity<ContractActivityAccountEditBinding, AccountEditModel> implements View.OnFocusChangeListener, TextWatcher {
    /**
     * 是否获取验证码
     */
    private boolean isGotCode = false;
    private int startIndex = 0;
    private String creditCode;

    @Override
    protected int getLayoutResId() {
        return R.layout.contract_activity_account_edit;
    }

    @Override
    protected void init() {
        initView();
        loadData();
    }

    private void initView() {
        mDataBinding.head.title.setText("修改经办人");
        mDataBinding.contractNewName.setOnFocusChangeListener(this);
        mDataBinding.contractNewName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                startIndex = start;
                if (!TextUtils.isEmpty(mDataBinding.contractNewName.getText().toString())) {
                    mDataBinding.contractTipName.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                int length = temp.length();
                if (!isLegalName(temp) && (length - 1) >= 0) {
                    s.delete(startIndex, startIndex + 1);
                }
            }
        });
        mDataBinding.contractIdNum.setOnFocusChangeListener(this);
        mDataBinding.contractIdNum.addTextChangedListener(this);
        mDataBinding.contractEdPhone.setOnFocusChangeListener(this);
        mDataBinding.contractEdPhone.addTextChangedListener(this);
        mDataBinding.contractVerificationCode.setOnFocusChangeListener(this);
        mDataBinding.contractVerificationCode.addTextChangedListener(this);
    }

    @SuppressLint("SetTextI18n")
    private void loadData() {
        Intent intent = getIntent();
        if (intent != null) {
            OpenAccountDetailEntity openAccountDetailEntity = (OpenAccountDetailEntity) intent.getSerializableExtra(AccountDetailActivity.KEY_DETAIL);
            mDataBinding.contractPreName.setText(openAccountDetailEntity.name);

            if (!TextUtils.isEmpty(openAccountDetailEntity.identityCard)) {
                String ID1 = openAccountDetailEntity.identityCard.substring(0, 4);
                String ID2 = openAccountDetailEntity.identityCard.substring(openAccountDetailEntity.identityCard.length() - 4);
                mDataBinding.contractPreId.setText(ID1 + "*********" + ID2);
            }

            if (!TextUtils.isEmpty(openAccountDetailEntity.phone) && openAccountDetailEntity.phone.length() == 11) {
                String pho1 = openAccountDetailEntity.phone.substring(0, 3);
                String pho2 = openAccountDetailEntity.phone.substring(openAccountDetailEntity.phone.length() - 4);
                mDataBinding.contractPrePhone.setText(pho1 + "****" + pho2);
            }
            creditCode = openAccountDetailEntity.creditCode;
        }
    }

    @Override
    protected void initListener() {
        mDataBinding.head.ivBack.setOnClickListener(v -> finish());
        mDataBinding.contractImageTip1.setOnClickListener(v -> {
            new RoundDialog.Builder(this)
                    .title("提示")
                    .content("企业电子签章的负责人")
                    .confirm("知道了")
                    .singleBtn(true)
                    .contentGravity(Gravity.CENTER)
                    .cancelable(true)
                    .show();
        });
        mDataBinding.contractImageTip2.setOnClickListener(v -> {
            new RoundDialog.Builder(this)
                    .title("提示")
                    .content("用于接收电子签章验证码的手机号，暂不支持修改")
                    .confirm("知道了")
                    .singleBtn(true)
                    .contentGravity(Gravity.CENTER)
                    .cancelable(true)
                    .show();
        });
        mDataBinding.contractTvCode.setOnClickListener(v -> {
                    if (TextUtils.isEmpty(mDataBinding.contractEdPhone.getText().toString().trim())) {
                        mDataBinding.contractTxtTipPhone.setText("请输入手机号码");
                        mDataBinding.contractTxtTipPhone.setVisibility(View.VISIBLE);
                        return;
                    }
                    isGotCode = true;
                    mViewModel.getValidateCode(mDataBinding.contractEdPhone.getText().toString().trim());
                }
        );

        mDataBinding.contractEditionConfirm.setOnClickListener(v -> {
            if (verification()) {
                //提交数据 待实现的方法
                Map<String, Object> paramMap = new HashMap<>(5);
                paramMap.put("creditCode", creditCode);
                paramMap.put("identityCard", mDataBinding.contractIdNum.getText().toString().trim());
                paramMap.put("name", mDataBinding.contractNewName.getText().toString().trim());
                paramMap.put("phone", mDataBinding.contractEdPhone.getText().toString().trim());
                paramMap.put("validateCode", mDataBinding.contractVerificationCode.getText().toString());
                mViewModel.updateAccount(paramMap);
            }
        });
    }

    private boolean verification() {
        if (TextUtils.isEmpty(mDataBinding.contractNewName.getText().toString().trim())) {
            mDataBinding.contractTipName.setVisibility(View.VISIBLE);
            return false;
        }

        if (TextUtils.isEmpty(mDataBinding.contractIdNum.getText().toString().trim())) {
            showTipIdTxt("请输入身份证号码");
            return false;
        }
        if (!StringUtils.idCardValidate(mDataBinding.contractIdNum.getText().toString().trim())) {
            showTipIdTxt("身份证号码格式错误");
            return false;
        }

        if (TextUtils.isEmpty(mDataBinding.contractEdPhone.getText().toString().trim())) {
            mDataBinding.contractTxtTipPhone.setText("请输入手机号码");
            mDataBinding.contractTxtTipPhone.setVisibility(View.VISIBLE);
            return false;
        }
        if (!isChinaPhoneLegal(mDataBinding.contractEdPhone.getText().toString().trim())) {
            mDataBinding.contractTxtTipPhone.setText("手机号码格式错误");
            mDataBinding.contractTxtTipPhone.setVisibility(View.VISIBLE);
            return false;
        }
        if (TextUtils.isEmpty(mDataBinding.contractVerificationCode.getText().toString())) {
            showTipCodeTxt("请输入验证码");
            return false;
        }
        if (!isGotCode) {
            showTipCodeTxt("验证码不存在，请获取验证码");
            return false;
        }
        return true;
    }

    @Override
    protected void initObserve() {
        mViewModel.validateCode.observe(this, integer -> {
            startTimer();
        });

        mViewModel.accountEditCode.observe(this, aBoolean -> {
            showTipDialog();
        });
    }

    private void startTimer() {
        CountDownTimer timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mDataBinding.contractTvCode.setEnabled(false);
                @SuppressLint("DefaultLocale") String str = String.format("重新获取(%1$d)", millisUntilFinished / 1000);
                mDataBinding.contractTvCode.setText(str);
                mDataBinding.contractTvCode.setTextColor(ContextCompat.getColor(AccountEditActivity.this, R.color.color_C0C4CC));
            }

            @Override
            public void onFinish() {
                mDataBinding.contractTvCode.setEnabled(true);
                mDataBinding.contractTvCode.setText("获取验证码");
                mDataBinding.contractTvCode.setTextColor(ContextCompat.getColor(AccountEditActivity.this, R.color.color_ffb79255));
            }
        };
        timer.start();
    }

    private void showTipDialog() {
        new RoundDialog.Builder(this)
                .title("提示")
                .content("修改成功")
                .confirm("知道了").confirmCallback(v -> {
            finish();
        })
                .singleBtn(true)
                .contentGravity(Gravity.CENTER)
                .cancelable(false)

                .show();
    }

    @Override
    protected void initViewModel() {
        mViewModel = createViewModel(AccountEditModel.class, BR.accountEditModel);
    }

    private void showTipIdTxt(String tx) {
        mDataBinding.contractTxtTipId.setVisibility(View.VISIBLE);
        mDataBinding.contractTxtTipId.setText(tx);
    }

    private boolean isChinaPhoneLegal(String phone) throws PatternSyntaxException {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[0-9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            return m.matches();
        }
    }

    public void showTipCodeTxt(String tx) {
        mDataBinding.contractTxtTipCode.setText(tx);
        mDataBinding.contractTxtTipCode.setVisibility(View.VISIBLE);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(mDataBinding.contractIdNum.getText().toString())) {
            mDataBinding.contractTxtTipId.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(mDataBinding.contractEdPhone.getText().toString())) {
            mDataBinding.contractTxtTipPhone.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(mDataBinding.contractVerificationCode.getText().toString())) {
            mDataBinding.contractTxtTipCode.setVisibility(View.GONE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            if (v.getId() == R.id.contract_new_name) {
                mDataBinding.contractTipName.setVisibility(View.GONE);
            } else if (v.getId() == R.id.contract_id_num) {
                mDataBinding.contractTxtTipId.setVisibility(View.GONE);
            } else if (v.getId() == R.id.contract_ed_phone) {
                mDataBinding.contractTxtTipPhone.setVisibility(View.GONE);
            } else if (v.getId() == R.id.contract_verification_code) {
                mDataBinding.contractTxtTipCode.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 验证输入的名字是否为“中文”或者是否包含“·”
     */
    public boolean isLegalName(String name) {
        if (name.contains("·") || name.contains("•")) {
            if (name.matches("^[\\u4e00-\\u9fa5]+[·•][\\u4e00-\\u9fa5]+$")) {
                return true;
            } else {
                return name.matches("[\\u4e00-\\u9fa5]+[·•]");
            }
        } else {
            return name.matches("^[\\u4e00-\\u9fa5]+$");
        }
    }

}